import React, { useEffect, useState, Component, useRef } from 'react';
import { fetchSync, request } from '@/utils/request';
import { history } from 'umi';
import { connect, router } from 'dva';
import { TinyColor } from '@ctrl/tinycolor';
import enUS from 'antd/es/locale/en_US';
import {
    Menu, Switch, Divider, Checkbox, Button, Row, Col, Tooltip, notification, Skeleton,
    Form, Modal, Select, Tree, Icon, Radio, Table, Tag, Pagination, Input, Space, message, Card, Tabs, Collapse, Image, ConfigProvider
} from 'antd';
import { MailOutlined, AppstoreOutlined, SettingOutlined, AudioOutlined, UserOutlined, ArrowRightOutlined, DownloadOutlined } from '@ant-design/icons';

import * as echarts from 'echarts';
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
import styles from './sports.less';
import * as turf from '@turf/turf';
import { Marker } from 'mapbox-gl';
import Mymenu from './mymenu';
import { getUserId, getUserName } from '@/utils/loginAssert';
import { size } from 'lodash';

let peoples = [
    [114.04945010962831, 22.54261376477976],
    [114.06298660992212, 22.52372419749328],
    [114.05110565282831, 22.531550188845515],
];
let activityRoute = {
    type: 'FeatureCollection',
    features: [
        {
            type: 'Feature',
            geometry: {
                type: 'LineString',
                coordinates: [[114.06288465542042, 22.542917645283694], [114.06312848046707, 22.531657435366256], [114.04977905914876, 22.531432221801936]]
            }
        }
    ]
};

const colors1 = ['#6253E1', '#04BEFE'];
const colors2 = ['#fc6076', '#ff9a44', '#ef9d43', '#e75516'];
const colors3 = ['#40e495', '#30dd8a', '#2bb673'];
const getHoverColors = (colors) =>
    colors.map((color) => new TinyColor(color).lighten(5).toString());
const getActiveColors = (colors) =>
    colors.map((color) => new TinyColor(color).darken(5).toString());

let switchGeolocateFlag = false;
let coorsFlag = []
export default (props) => {
    const [map, setMap] = useState(null);
    const [users, setUsers] = useState([]);
    const [markers, setMarkers] = useState([]);
    const mapContainer = useRef(null);
    const echarts1 = useRef(null);
    const commentList = useRef(null);
    const [switchGeolocate, setSwitchGeoLocate] = useState(false)
    const [coors, setCoors] = useState([])

    const [activeItem, setActiveItem] = useState({})
    const [myActivities, setMyActivities] = useState([])

    //初始函数
    useEffect(async () => {
        //此处编写 组件挂载之后和组件重新渲染之后执行的代码
        let data = await fetchSync('/api/user/findAll')
        setUsers(data.data);

        initActivities();
        initMap()
        return () => {
            //此处编写 组件即将被卸载前执行的代码
        }
        // 4、若传值，但是传的是空数组 []，则表示该useEffect里的内容仅会在“挂载完成后和组件即将被卸载前”执行一次；
    }, [])

    const initMap = () => {
        if (!mapContainer.current) return;
        mapboxgl.accessToken = 'pk.eyJ1IjoicGluZ2Fuc2hhbiIsImEiOiJja2x3M2ZkcHkweXBpMndwOWZ4ZjQ1NTFoIn0.vDeeNsG4fOoX6M8HT5mLCA';
        const map = new mapboxgl.Map({
            container: mapContainer.current,
            style: 'mapbox://styles/mapbox/dark-v9',
            center: [104.04912680278238, 30.708415938863226],
            zoom: 12.817795563755116,
            dragPan: true,
            dragRotate: false,
            renderWorldCopies: false,
            // projection: 'naturalEarth',
            // maxBounds: [[-280, -90], [280, 90]],
        });
        window.map = map;
        map.on('load', () => {
            // peoples.forEach((peo, idx)=>{
            //     const el = document.createElement('div')
            //     // elAll.style = 'padding:0px;max-width: 400px; background: #fff; padding: 10px; border-radius: 10px;'
            //     el.innerHTML = `<img src=${require("./img/head" +(idx+1)+ ".png")} width="50%"/>`
            //     new mapboxgl.Marker(el).setLngLat(peo).addTo(map)
            // })

            map.addSource('activityRoute', {
                type: 'geojson',
                data: {
                    type: 'FeatureCollection',
                    features: []
                }
            });

            map.addSource('myRoute', {
                type: 'geojson',
                data: {
                    type: 'FeatureCollection',
                    features: []
                }
            });

            map.addLayer({
                'id': 'Layer',
                'source': 'activityRoute',
                'type': 'line',
                layout: {
                    visibility: 'visible',
                },
                'paint': {
                    // 'line-color': ['#D22525', '#2ABC17', '#F7CB27'][parseInt(Math.random() * 3)],
                    'line-color': '#1677ff',
                    'line-width': 5,
                }
            })

            map.addLayer({
                'id': 'myRouteLayer',
                'source': 'myRoute',
                'type': 'line',
                layout: {
                    visibility: 'visible',
                },
                'paint': {
                    'line-color': '#2ABC17',
                    'line-width': 3,
                }
            })
        });
        map.on('click', (e) => {
            console.log(e)
        })

        const geolocate = new mapboxgl.GeolocateControl({
            positionOptions: {
                enableHighAccuracy: true
            },
            // When active the map will receive updates to the device's location as it changes.
            trackUserLocation: true,
            // Draw an arrow next to the location dot to indicate which direction the device is heading.
            showUserHeading: true
        })

        map.addControl(geolocate);
        // let count = 0;
        geolocate.on('geolocate', (e) => {
           
            if (!switchGeolocateFlag) {
                // message.info('1')
            } else {
                // message.info('2')
                // console.log('A geolocate event has occurred.');
                var lon = e.coords.longitude;
                var lat = e.coords.latitude
                // count ++;
                setCoors([...coors, [lon, lat]])
                coorsFlag.push([lon, lat])
                // message.info(JSON.stringify(coorsFlag))

                map.getSource('myRoute').setData({
                    type:'FeatureCollection',
                    features:[{
                        type:'Feature',
                        geometry:{
                            type:'LineString',
                            coordinates:coorsFlag
                            // coordinates: [[114.06288465542042, 22.542917645283694], [114.06312848046707, 22.531657435366256], [114.04977905914876, 22.531432221801936]]
                        }
                    }]
                })

                // {
                //     type: 'Feature',
                //     geometry: {
                //         type: 'LineString',
                //         coordinates: [[114.06288465542042, 22.542917645283694], [114.06312848046707, 22.531657435366256], [114.04977905914876, 22.531432221801936]]
                //     }
                // }
            }
        });
        setMap(map)
    }

    const initActivities = () => {
        request('/api/joy/activity/findAll', {
            method: 'get'
        }).then(res => {
            if (res.success) {
                // let data = res.data.filter(item => (item.userId == getUserId()) || ((item.userId != getUserId()) && (item.userNames) && (item.userNames.indexOf(getUserName()) != -1)))
                let data = res.data.filter(item => (item.userNames) && (item.userNames.indexOf(getUserName()) != -1))
                setMyActivities(data || [])
            }
        })
    }

    const clearMap = () => {
        if (!map) return;
        if (map.getLayer('taifengPointLayer')) map.removeLayer('taifengPointLayer');
        if (map.getSource('taifengPointSource')) map.removeSource('taifengPointSource');
    }
    const clickItem = (item) => {
        setActiveItem(item)
        // 更新路线
        let feature = JSON.parse(`{
            "type":"Feature",
            "geometry": {
                "type":"LineString",
                "coordinates": [ ${item['routes']} ]
            }
        }`)
        map.getSource('activityRoute').setData({
            type: 'FeatureCollection',
            features: [feature]
        })
        // 更新头像
        let usernames = item.userNames
        usernames.splice(usernames.indexOf(getUserName()), 1)
        let markers = []
        usernames.forEach((name, idx) => {
            const el = document.createElement('div')
            let user = users.find(u => u.username = name)
            if (user) {

                el.innerHTML = `<img src=${user?.avatarImg || require("./img/head1.png")} width="50%"/>`
                
                var line = turf.lineString(feature.geometry.coordinates);
                var bbox = turf.bbox(line);
                var points = turf.randomPoint(1, { bbox })
                console.log(points)
                let marker = new mapboxgl.Marker(el).setLngLat(points.features[0].geometry.coordinates).addTo(map)
                markers.push(marker)
            }
        })
        map.flyTo({
            center: feature.geometry.coordinates[0],
            zoom: 13,
            bearing: 0,
            screenSpeed: 1.5, // make the flying slow
            curve: 2, // change the speed at which it zooms out
            easing: (t) => t,
            essential: true,
        })
        setMarkers(markers)
    }

    // useEffect(() => {
    //     if (switchGeolocate) { // start
    //         setCoors([...coors, [114, 23], [114, 23.1]])
    //     } else { // finish

    //     }
    //     console.log(coors)
    // }, [switchGeolocate])

    const sportsFun = () => {
        switchGeolocateFlag = !switchGeolocateFlag
        setSwitchGeoLocate(!switchGeolocate)
    }

    // 导出数据
    const downLoadRoute = ()=>{

        let dataCopy = {
            type:'FeatureCollection',
            features:[{
                type:'Feature',
                geometry:{
                    type:'LineString',
                    coordinates:coors
                }
            }]
        }
        console.log(dataCopy);
        if (typeof dataCopy === 'object') {
            dataCopy = JSON.stringify(dataCopy, null, 4);
        }
        const blob = new Blob([dataCopy], { type: 'text/json' });
        const e = new MouseEvent('click');
        const a = document.createElement('a');

        a.download = 'myRoute.json';
        a.href = window.URL.createObjectURL(blob);
        a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
        a.dispatchEvent(e);

        setCoors([])
        coorsFlag=[]
        map.getSource('myRoute').setData({
            type:'FeatureCollection',
            features:[{
                type:'Feature',
                geometry:{
                    type:'LineString',
                    coordinates:[]
                }
            }]
        })
    }

    return (
        <div className={styles.container}>
            {
                activeItem.activityType && (activeItem.activityType != '') && <div className={styles.type}>
                    {activeItem.activityType}
                </div>
            }
            {
                myActivities?.length > 0 && <Card border={false} style={{ top: 100, left: 5, position: 'absolute', zIndex: 111, maxWidth: 240, maxHeight: '400px', overflowY: 'auto' }}>
                    {
                        myActivities.map((it, index) => {
                            return <div key={index} style={{ fontSize: 16, color: activeItem.name == it.name ? '#1677ff' : '' }} onClick={() => clickItem(it)}>{it.name}</div>
                        })
                    }
                </Card>
            }

            <ConfigProvider
                theme={{
                    components: {
                        Button: {
                            colorPrimary: `linear-gradient(90deg,  ${colors2.join(', ')})`,
                            colorPrimaryHover: `linear-gradient(90deg, ${getHoverColors(colors2).join(', ')})`,
                            colorPrimaryActive: `linear-gradient(90deg, ${getActiveColors(colors2).join(', ')})`,
                            lineWidth: 0,
                        },
                    },
                }}

            >
                <Button type="primary" size="large" style={{ position: 'absolute', bottom: 120, zIndex: 111, width: 200, left: 0, right: 0, margin: 'auto' }} onClick={sportsFun}>
                    {
                        switchGeolocate ? 'FINISH' : 'START'
                    }
                </Button>
            </ConfigProvider>
            {
                !switchGeolocate && (coors.length > 0) && <Button type="primary" icon={<DownloadOutlined /> } size={'large'} onClick={downLoadRoute}
                    style={{ position: 'absolute', bottom: 120, zIndex: 111,  right: 20, margin: 'auto' }}
                />
            }
            <div ref={mapContainer} className={styles.mapContainer}></div>
        </div>
    );
}
